package com.djl.Zookeeper.util;

import com.djl.Zookeeper.watch.DefaultWatch;
import org.apache.zookeeper.ZooKeeper;

import java.util.concurrent.CountDownLatch;

public class ZkUtil {

    private static ZooKeeper zooKeeper;
    /**
     * 连接地址
     */
    private static String address = "192.168.133.132:2181,192.168.133.133:2181,192.168.133.134:2181,192.168.133.135:2181";

    private static String address_alone = "192.168.133.132:2181/lockNode";

    private static DefaultWatch defaultWatch = new DefaultWatch();

    private static CountDownLatch countDownLatch = new CountDownLatch(1);

    /**
     * 集群模式
     */
    public static ZooKeeper getZookeeper(){
        try {
            zooKeeper = new ZooKeeper(address, 1000, defaultWatch);
            defaultWatch.setCountDownLatch(countDownLatch);
            countDownLatch.await();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return zooKeeper;
    }

    /**
     * 单机模式
     */
    public static ZooKeeper getAloneZookeeper(){
        try {
            zooKeeper = new ZooKeeper(address_alone, 1000, defaultWatch);
            defaultWatch.setCountDownLatch(countDownLatch);
            countDownLatch.await();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return zooKeeper;
    }
}
